# coding:utf-8

import httplib
import MySQLdb
import sys,os,re
from datetime import timedelta, date
import datetime
import time

#t1 = time.mktime(time.strptime("03:12:32","%H:%M:%S"))
#t2 = time.mktime(time.strptime("03:11:42","%H:%M:%S"))
#print t1, t2, t1 - t2
#sys.exit()
#http://quote.stock.hexun.com/stockdata/stock_quote.aspx?stocklist=002628

#http://money.finance.sina.com.cn/quotes_service/view/vMS_tradedetail.php?symbol=sz300272&date=2012-12-12&page=1

def getDetailPage(stockcode, page, d=""):
  conn = httplib.HTTPConnection("money.finance.sina.com.cn")
  flag="sh"
  if stockcode[0]!='6':
    flag="sz"
  url=""
  if d=="":
    url = "/quotes_service/view/vMS_tradedetail.php?symbol=%s%s&page=%d" % (flag, stockcode, page)
  else:
    url = "/quotes_service/view/vMS_tradehistory.php?symbol=%s%s&page=%d&date=%s" % (flag, stockcode, page, d)
  print url
  conn.request("GET", url)
  r1 = conn.getresponse()
  data = r1.read()
  data=data.decode('gb18030')
  pos2=data.rfind("</tbody")
  pos1=data.rfind("<tbody")
  data=data[pos1:pos2]
  #data=data.replace("<td>", " ").replace("</td>", " ").replace("<th>", " ").replace("</th>", " ").replace("<tr >", " ").replace("</tr>", " ")
  res=dict()
  if len(data)<100:
    return res 
  seq=data.split("\n")
  for i in seq:
    p=re.compile(".*?([0-9]*:[0-9]*:[0-9]*).*([+|-].*%).*?</td>.*?</td>.*?([0-9]+).*<h[0-9]>(.*)</h[0-9]>")
    m=p.match(i)
    if m:
      #print m.group(4)
      k=m.group(1)
      w=float(m.group(2)[:-1])
      l=int(m.group(3))
      if k not in res:
        res[k]=[w,l,m.group(4)]
      else:
        res[k]=[w,res[k][1]+l, m.group(4)]
      #if k not in res:
      #  res[k] = [w, w, l]
      #else:
      #  res[k] = [w, res[k][1], res[k][2]+l]
  return res
def getDetails(stockcode, d=""):
  count=1
  res=dict()
  while 1:
    tmp=getDetailPage(stockcode, count, d)
    if len(tmp)==0:
      break
    for i in tmp:
      if i not in res:
        res[i]=[tmp[i][0], tmp[i][1]]
      else:
        res[i]=[res[i][0], res[i][1]+tmp[i][1]]
    count+=1
  return res

def loadData(code, load=True, d=""):
  res=dict()
  if os.path.isfile("data/%s.%s"%(code, d)):
    f=open("data/%s.%s"%(code, d))
    lines=f.readlines()
    for i in lines:
      seq=i.decode("UTF-8").strip().split()
      if len(seq) < 4:
        continue
      res[seq[0]] = [float(seq[1]), int(seq[2]), seq[3]]
    f.close()
  print "load from file ", code, " ", len(res)
  if not load:
    return res
  #return res
  tmpres=dict()
  count=1
  flag=False
  while 1:
    tmp=getDetailPage(code, count, d)
    if len(tmp)==0:
      break
    for i in tmp:
      if i not in res:
        tmpres[i]=[tmp[i][0], tmp[i][1], tmp[i][2]]
      else:
        print "break"
        flag=True
        break
    count+=1
    if flag:
      break

  for i in tmpres:
    res[i] = [tmpres[i][0], tmpres[i][1], tmpres[i][2]]

  keys=res.keys()
  keys.sort()
  f=open("data/%s.%s"%(code,d), "wr")
  for i in keys:
    rd = "%s %.2f %d %s\n"%(i, res[i][0], res[i][1], res[i][2])
    f.write(rd.encode("UTF-8"))
    #f.write(rd)
  f.close()
  return res

#keys=res.keys()
#keys.sort()

def checkPoint(begin, keys, res):
  stepbegin=begin
  if begin > len(keys):
    return False
  pos1=keys[-stepbegin].find("14")
  pos2=keys[-stepbegin].find("13")
  if pos1<0 and pos2<0:
    return False
    
  t = time.mktime(time.strptime(keys[-stepbegin], "%H:%M:%S"))
  #print "begin ", keys[-stepbegin]
  begintime = keys[-stepbegin]
  wave = res[keys[-stepbegin]][0]
  flag=0
  while stepbegin<len(keys):
    k = keys[-stepbegin]
    v = res[k]
    t1 = time.mktime(time.strptime(k, "%H:%M:%S"))
    #print "step ", k, wave, v 
    #print t1, t, t1-t
    if t - t1 > 60:
      #print "end ", k, stepbegin
      break
    if wave-v[0] < -1:
      print "down ", begintime, k, stepbegin
      flag=1
      break 
    stepbegin+=1
  if not flag:
    return False
  sum1=0
  sum2=0
  c=0
  while c<len(keys)-begin:
    k = keys[c]
    v = res[k]
    if c<len(keys)-stepbegin:
      sum1+=v[1]
    if c>len(keys)-stepbegin:
      sum2+=v[1]
    c+=1
  #print stepbegin, len(keys)
  mean1=sum1/(len(keys)-stepbegin)
  mean2=sum2/(stepbegin-begin)
  c=begin
  buybigdeal=0
  while c<=stepbegin:
    k = keys[-c]
    v = res[k]
    #print v[1], mean1
    if v[1]>5*mean1:# and v[2]=="买单":
      #print mean1, v[1]
      buybigdeal+=1
    c+=1
  #print begin, stepbegin, stepbegin-begin, mean1, mean2, buybigdeal
  #print sum1, sum2, mean1, mean2
  #print begintime, keys[-stepbegin], mean1, mean2
  #if mean2>5*mean1 and stepbegin>5:
  #if (mean2>20*mean1 and mean2<50*mean1) or (buybigdeal>=5 and mean2>10*mean1):
  if (buybigdeal>=5 and mean2>10*mean1):
    print "succ ", begintime, keys[-stepbegin], wave, mean1, mean2, buybigdeal 
    return True
  return False 
#checkPoint(1, keys, res)
